<?php

namespace App\Http\Controllers\Api\Teacher;

use App\Models\Course;
use App\Models\CourseCategory;
use App\Models\Knowledge;
use App\Models\Paper;
use App\Models\Question;
use App\Models\PracticalParam;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class CourseController extends Controller
{
    /**
     * 课程列表（带统计数据）
     * GET /api/teacher/courses
     */
    public function index(Request $request)
    {
        // 请求参数
        $name = $request->input('name'); // 课程名搜索
        $categoryId = $request->input('category_id'); // 分类筛选
        $status = $request->input('status', 1);
        $page = $request->input('page', 1);
        $pageSize = $request->input('page_size', 10);

        // 查询当前教师的课程
        // $query = Course::with(['category:id,name', 'knowledges:id,title', 'papers:id,name', 'students:id,name'])
        //                 ->where('teacher_id', auth('admin')->id());
        $query = Course::with(['category:id,name', 'knowledges:id,title', 'papers:id,name', 'students:id,name']);

        // 搜索条件
        if (!empty($name)) {
            $query->where('name', 'like', "%{$name}%");
        }
        if (!empty($categoryId)) {
            $query->where('category_id', $categoryId);
        }
        if (isset($status)) {
            $query->where('status', $status);
        }

        // 分页查询
        $courses = $query->paginate($pageSize, ['*'], 'page', $page);
        $courseItems = $courses->items();

        // 计算关联数量
        foreach ($courseItems as $course) {
            $course->knowledge_count = $course->knowledgeCount;
            $course->paper_count = $course->paperCount;
            $course->student_count = $course->studentCount;
        }

        return $this->paginated($courseItems, $courses);
    }

    /**
     * 课程分类列表
     * GET /api/teacher/course-categories
     */
    public function categoryList(Request $request)
    {
        $name = $request->input('name'); // 分类名搜索
        $query = CourseCategory::where('status', 1);

        if (!empty($name)) {
            $query->where('name', 'like', "%{$name}%");
        }

        return $this->success($query->get());
    }

    /**
     * 课程详情（含关联的学生/知识/试卷）
     * GET /api/teacher/course-detail
     */
    public function detail(Request $request)
    {
        $request->validate([
            'id' => 'required|integer|exists:courses,id'
        ]);

        $course = Course::with([
            'category:id,name',
            'knowledges:id,title,type,is_wps', // 关联知识(包含is_wps字段用于区分理论知识和WPS)
            'papers:id,name,duration,type', // 关联试卷(包含type字段: 0=随堂测验, 1=考试)
            'students:id,name,username,phone', // 关联学生
            'practicalParam' // 关联实训参数
        ])->findOrFail($request->input('id'));

        // 验证课程归属
        // if ($course->teacher_id != auth('admin')->id()) {
        //     return $this->error('无权查看此课程', 403);
        // }

        return $this->success($course);
    }

    /**
     * 新增/编辑课程（含关联知识、试卷）
     * POST/PUT /api/teacher/courses
     */
    public function save(Request $request)
    {
        $request->validate([
            'id' => 'nullable|integer|exists:courses,id',
            'name' => 'required|string|max:100',
            'category_id' => 'nullable|integer|exists:course_categories,id',
            'category' => 'required_if:category_id,null|string|max:50',
            'status' => 'boolean',
            'knowledge_ids' => 'nullable|array', // 关联知识ID数组
            'knowledge_ids.*' => 'integer|exists:knowledges,id',
            'papers' => 'nullable|array', // 试卷数组
            'papers.*.id' => 'nullable|integer|exists:papers,id', // 已有试卷ID
            'papers.*.name' => 'required_with:papers.*.duration,papers.*.type,papers.*.question_ids|string|max:100', // 新试卷名称
            'papers.*.duration' => 'required_with:papers.*.name,papers.*.type,papers.*.question_ids|integer', // 新试卷时长
            'papers.*.type' => 'required_with:papers.*.name,papers.*.duration,papers.*.question_ids|in:0,1', // 新试卷类型
            'papers.*.question_ids' => 'required_with:papers.*.name,papers.*.duration,papers.*.type|array', // 新试卷题目ID数组
            'papers.*.question_ids.*' => 'integer|exists:questions,id', // 题目ID
            // 实训参数验证规则
            'practical_param' => 'nullable|array',
            'practical_param.difficulty' => 'required_with:practical_param|integer|in:1,2,3',
            'practical_param.weld_joint' => 'nullable|string|max:100',
            'practical_param.position' => 'nullable|string|max:100',
            'practical_param.material' => 'nullable|string|max:100',
            'practical_param.thickness' => 'nullable|numeric',
            'practical_param.welding_method' => 'nullable|string|max:100',
            'practical_param.filler_material' => 'nullable|string|max:100',
            'practical_param.gas_type' => 'nullable|string|max:100',
            'practical_param.weld_length' => 'nullable|numeric',
            'practical_param.weld_layers' => 'nullable|integer',
            'practical_param.remark' => 'nullable|string|max:500'
        ]);

        $teacherId = auth('admin')->id();
        $courseId = $request->input('id');

        // 处理分类逻辑
        $categoryId = $request->input('category_id');
        if (empty($categoryId)) {
            // 如果category_id为空，则创建新分类
            $category = CourseCategory::create([
                'name' => $request->input('category'),
                'status' => 1
            ]);
            $categoryId = $category->id;
        }

        // 新增/更新课程基本信息
        $course = Course::updateOrCreate(
            ['id' => $courseId],
            [
                'name' => $request->input('name'),
                'category_id' => $categoryId,
                'teacher_id' => $teacherId,
                'status' => $request->input('status', 1)
            ]
        );

        // 关联知识（同步：清空原有关联，添加新关联）
        if ($request->has('knowledge_ids')) {
            $course->knowledges()->sync($request->input('knowledge_ids'));
        }

        // 处理试卷关联
        if ($request->has('papers')) {
            $paperIds = [];
            foreach ($request->input('papers') as $paperData) {
                if (isset($paperData['id'])) {
                    // 直接使用已有试卷ID
                    $paperIds[] = $paperData['id'];
                } else if (isset($paperData['name']) && isset($paperData['duration']) && isset($paperData['type']) && isset($paperData['question_ids'])) {
                    // 创建新试卷
                    $paper = Paper::create([
                        'name' => $paperData['name'],
                        'duration' => $paperData['duration'],
                        'type' => $paperData['type'],
                        'teacher_id' => $teacherId,
                        'status' => 1
                    ]);
                    
                    // 关联题目到新创建的试卷
                    $paper->questions()->sync($paperData['question_ids']);
                    
                    $paperIds[] = $paper->id;
                }
            }
            
            // 同步试卷关联
            $course->papers()->sync($paperIds);
        }

        // 处理实训参数
        if ($request->has('practical_param')) {
            $paramData = $request->input('practical_param');
            $paramData['course_id'] = $course->id;
            
            PracticalParam::updateOrCreate(
                ['course_id' => $course->id],
                $paramData
            );
        }

        $message = $courseId ? '课程更新成功' : '课程创建成功';
        return $this->success($course, $message);
    }

    /**
     * 辅助接口：获取可选知识列表（供课程绑定）
     * GET /api/teacher/available-knowledges
     */
    public function availableKnowledges(Request $request)
    {
        // $knowledges = Knowledge::where('teacher_id', auth('admin')->id())
        //                     ->where('status', 1)
        //                     ->get(['id', 'title', 'type']);
        $knowledges = Knowledge::where('status', 1)
                            ->where('is_wps', 0)
                            ->get(['id', 'title', 'type']);
        return $this->success($knowledges);
    }

    /**
     * 辅助接口：获取可选试卷列表（供课程绑定）
     * GET /api/teacher/available-papers
     */
    public function availablePapers(Request $request)
    {
        // $papers = Paper::where('teacher_id', auth('admin')->id())
        //               ->where('status', 1)
        //               ->get(['id', 'name', 'duration']);
        $papers = Paper::where('status', 1)
                      ->get(['id', 'name', 'duration']);
        return $this->success($papers);
    }
}